package com.showworkflow.controller;

import org.apache.poi.xwpf.usermodel.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:5174", "http://localhost:5175"})
@RestController
@RequestMapping("/api/generated")
public class GeneratedFileController {

    private final Path fileStorageLocation;
    
    public GeneratedFileController() {
        // 使用相对于当前工作目录的路径
        Path mainPath = Paths.get("src/main/resources/generated").toAbsolutePath().normalize();

        // 如果不存在，尝试backend前缀的路径
        if (!Files.exists(mainPath)) {
            mainPath = Paths.get("backend/src/main/resources/generated").toAbsolutePath().normalize();
        }

        this.fileStorageLocation = mainPath;
        System.out.println("GeneratedFileController: 文件存储路径 = " + this.fileStorageLocation);
    }

    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("GeneratedFileController is working");
    }

    @GetMapping("/{fileName:.+}/html")
    public ResponseEntity<String> getFileAsHtml(@PathVariable String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();

            if (!Files.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }

            // 转换Word文档到HTML
            String htmlContent = convertWordToHtml(filePath);

            return ResponseEntity.ok()
                    .contentType(MediaType.TEXT_HTML)
                    .body(htmlContent);

        } catch (Exception ex) {
            System.err.println("转换HTML时出错: " + ex.getMessage());
            ex.printStackTrace();
            return ResponseEntity.internalServerError()
                    .body("<html><body><h1>文档转换失败</h1><p>无法将Word文档转换为HTML格式</p></body></html>");
        }
    }

    private String convertWordToHtml(Path filePath) throws Exception {
        try (InputStream is = Files.newInputStream(filePath);
             XWPFDocument document = new XWPFDocument(is)) {

            StringBuilder html = new StringBuilder();
            html.append("<!DOCTYPE html>");
            html.append("<html><head>");
            html.append("<meta charset='UTF-8'>");
            html.append("<meta name='viewport' content='width=device-width, initial-scale=1.0'>");
            html.append("<title>文档预览</title>");
            html.append("<style>");
            html.append("body { font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 20px; line-height: 1.6; }");
            html.append("table { border-collapse: collapse; width: 100%; margin: 10px 0; }");
            html.append("td, th { border: 1px solid #ddd; padding: 8px; text-align: left; }");
            html.append("th { background-color: #f2f2f2; font-weight: bold; }");
            html.append("p { margin: 10px 0; }");
            html.append(".center { text-align: center; }");
            html.append(".bold { font-weight: bold; }");
            html.append("</style>");
            html.append("</head><body>");

            // 处理文档内容
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                String text = paragraph.getText();
                if (text != null && !text.trim().isEmpty()) {
                    String alignment = getAlignmentClass(paragraph.getAlignment());
                    html.append("<p class=\"").append(alignment).append("\">");
                    html.append(escapeHtml(text));
                    html.append("</p>");
                }
            }

            // 处理表格
            List<XWPFTable> tables = document.getTables();
            for (XWPFTable table : tables) {
                html.append("<table>");
                for (XWPFTableRow row : table.getRows()) {
                    html.append("<tr>");
                    for (XWPFTableCell cell : row.getTableCells()) {
                        String cellText = cell.getText();
                        html.append("<td>").append(escapeHtml(cellText)).append("</td>");
                    }
                    html.append("</tr>");
                }
                html.append("</table>");
            }

            html.append("</body></html>");
            return html.toString();

        } catch (Exception e) {
            throw new Exception("Word转HTML失败: " + e.getMessage(), e);
        }
    }

    private String getAlignmentClass(ParagraphAlignment alignment) {
        if (alignment == null) return "";
        switch (alignment) {
            case CENTER:
                return "center";
            case RIGHT:
                return "right";
            default:
                return "";
        }
    }

    private String escapeHtml(String text) {
        if (text == null) return "";
        return text.replace("&", "&amp;")
                  .replace("<", "&lt;")
                  .replace(">", "&gt;")
                  .replace("\"", "&quot;")
                  .replace("'", "&#39;");
    }

    @GetMapping("/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists()) {
                // 根据文件扩展名确定正确的MIME类型
                MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
                if (fileName.endsWith(".docx")) {
                    mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                } else if (fileName.endsWith(".doc")) {
                    mediaType = MediaType.parseMediaType("application/msword");
                }

                return ResponseEntity.ok()
                        .contentType(mediaType)
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename*=UTF-8''" + URLEncoder.encode(resource.getFilename(), StandardCharsets.UTF_8.toString()))
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception ex) {

            return ResponseEntity.internalServerError().build();
        }
    }
}